package com.nulldev.util.languages.csv_legacy;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.LinkedList;
import java.util.regex.Pattern;

import com.nulldev.util.VariableAPI.ArrayUtils;
import com.nulldev.util.manage.MarkedForRemoval;

@MarkedForRemoval(reason = "Replaced by the newer CSV API", plannedRemovalWhen = "3.1")
public class LegacyCSV {
	public LegacyCSV() {
	}

	private static final Pattern csv_parse = Pattern.compile(",(?=([^\\\"]*\\\"[^\\\"]*\\\")*(?![^\\\"]*\\\"))");

	private boolean keepQuotes;
	private final LinkedList<LinkedList<String>> csv_entries = new LinkedList<LinkedList<String>>();

	public void read(final File f) throws Exception {
		if (!this.csv_entries.isEmpty()) {
			this.csv_entries.clear();
		}
		final FileReader fr = new FileReader(f);
		final BufferedReader br = new BufferedReader(fr);

		String line;
		while ((line = br.readLine()) != null) {
			if (!line.startsWith("//")) {
				// final Matcher m = csv_parse.matcher(line);
				String[] values = csv_parse.split(line); // new String[] {};
//				int i = 0;
//				while (m.find()) {
//					values = ArrayUtils.add(values, m.group());
//					i += 1;
//				}
				final LinkedList<String> v = new LinkedList<String>();
				for (final String value : values) {
					if (keepQuotes) {
						v.add(value);
					} else {
						if (value.startsWith("\"") && value.endsWith("\"")) {
							v.add(value.substring(1, value.length() - 1));
						} else if (value.contains("\"")) {
							v.add(value.replaceAll(Pattern.quote("\""), ""));
						} else {
							v.add(value);
						}
					}
				}
				this.csv_entries.add(v);
			}
		}

		br.close();
		fr.close();
	}

	@SuppressWarnings("unchecked")
	public LinkedList<LinkedList<String>> clone() {
		return (LinkedList<LinkedList<String>>) this.csv_entries.clone();
	}

	public LinkedList<String> read(final int position) {
		if (position < 0 || position > this.csv_entries.size() - 1) {
			return new LinkedList<String>();
		}
		return this.csv_entries.get(position);
	}

	public void printlnf() {
		ArrayUtils.printLln(this.csv_entries);
	}

	public int entries() {
		return this.csv_entries.size();
	}
}
